package com.itic.mall.mobile.pay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.type.FinanceType;
import com.itic.appbase.framework.type.WithDrawalsType;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.pay.userlog.persistence.model.PayUserlog;
import com.itic.mall.system.pay.userlog.service.PayUserlogService;
import com.itic.mall.system.pay.withDrawals.persistence.model.WithDrawalsRecord;
import com.itic.mall.system.pay.withDrawals.service.WithDrawalsRecordService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
@Controller
@RequestMapping(value="/mobile/withDrawals")
public class WithDrawalsInterface extends BaseMobileInterface{
	@Autowired
	private UsersMallService usersMallService;
	@Autowired
	private PayUserlogService payUserLogService;
	@Autowired
	private WithDrawalsRecordService withDrawalsRecordService;
	
	@RequestMapping(value="ali/fee")
	@ResponseBody
	public Map<String, Object> getFee(HttpServletResponse response,String token,String appId) {
		Map<String, Object> resultMap = new HashMap<>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			UsersMall usersMall= this.getUsersByTokenAndAppId(token, appId);
			if(usersMall!=null) {
				double fee= this.getFeeAmount();
				List<PayUserlog>theLastWithDrawals = this.payUserlogService.getWithDrawals(usersMall.getId());
				if(theLastWithDrawals.isEmpty())
					fee = 0;
				resultMap.put(DATA, fee);
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
			}else {
				errorCode = LOGIN_ERROR_CODE;
		       	errorMsg = LOGIN_ERROR_MSG;
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("WithDrawalsInterface", "getFee", e.toString(), "获取用户所需的手续费", e);
		
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	
	private double getFeeByUserId(String userId) {
		double fee= this.getFeeAmount();
		List<PayUserlog>theLastWithDrawals = this.payUserlogService.getWithDrawals(userId);
		if(theLastWithDrawals.isEmpty())
			fee = 0;
		return fee;
	}
	
	@RequestMapping(value="ali/apply")
	@ResponseBody
	public Map<String, Object> applyWithDrawals(HttpServletResponse response,String token,String appId,String aliName,String aliAccount,String phone,String code,Double amount){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(token,appId,aliName,aliAccount,phone,code) && amount!=null) {
				if(isEffectiveCode(phone, code)) {
					UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
					if(usersMall !=null) {
						double balance = usersMall.getMoney() == null?0:usersMall.getMoney();
						//获取用户最后一次提现
						double fee = this.getFeeByUserId(usersMall.getId());
						boolean isWithDrawals = this.checkIsWithDrawals(balance, amount,fee);
						if(isWithDrawals) {
							//获取用户支付最后一调记录
							PayUserlog payUserlogTemp = this.payUserlogService.getTheLastPayUserLog(usersMall.getId());
							//获取提现总额
							double totalWithDrawals = payUserlogTemp==null?0:payUserlogTemp.getWithdrawTotalAmount()==null?0:payUserlogTemp.getWithdrawTotalAmount();
							//添加提现
							PayUserlog payUserlog = this.payUserlogService.addWithDrawals(totalWithDrawals, balance, amount, fee, usersMall.getId());
							//添加提现记录
							withDrawalsRecordService.addWithDrawalsRecord(amount, aliName, aliAccount,payUserlog.getId(), phone, fee, usersMall.getId());;
							//TODO 用户表减少余额
							usersMall.setMoney(balance-amount);
							this.usersMallService.edit(usersMall);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else{
							errorCode = Amount_NOT_FEE_CODE;
							errorMsg = Amount_NOT_FEE_MSG;
						}
					}else {
						errorCode = LOGIN_ERROR_CODE;
				       	errorMsg = LOGIN_ERROR_MSG;
					}
				}else {
					errorCode = PHONE_CODE_ERROR_CODE;
			       	errorMsg = PHONE_CODE_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("WithDrawalsInterface", "applyWithDrawals", e.toString(), "申请退款接口", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	private boolean checkIsWithDrawals(double balance,double amount,double fee) {
		double money = this.getlessMoneyNotWithDraw();
		boolean flag = this.getIsOpenLessMoneyNotWithDraw();
		if(flag && balance<money) 
			return false;
		if(balance<=0 || balance<fee || amount>balance || amount<fee)	
			return false;
		return true;
	}
}
